import os
from urllib.parse import quote_plus

# 获取当前环境，默认为开发环境
ENV = os.getenv("ENV", "dev")

# 导入common配置
from common.config import LLM_CONFIG, USE_SILICONFLOW


# 构建数据库URL，处理密码中的特殊字符
def build_database_url(user, password, host, port, database):
    # 对密码进行URL编码，处理特殊字符如 @ # % 等
    encoded_password = quote_plus(password)
    return f"mysql+mysqlconnector://{user}:{encoded_password}@{host}:{port}/{database}"


# 数据库连接池配置
DB_POOL_CONFIG = {
    "pool_size": 50,  # 增加连接池大小
    "max_overflow": 20,  # 增加最大溢出连接数
    "pool_timeout": 60,  # 增加连接超时时间
    "pool_recycle": 3600,  # 连接回收时间
    "echo": False,  # 关闭SQL语句日志
}

# 环境配置（优先使用 LETTER_DB_* 环境变量，带有安全默认值）
config = {
    "dev": {
        "host": "localhost",
        "port": 8106,
        "db_pool": DB_POOL_CONFIG,
        "database_url": build_database_url(
            os.getenv("LETTER_DB_USER", "root"),
            os.getenv("LETTER_DB_PASSWORD", "root"),
            os.getenv("LETTER_DB_HOST", "localhost"),
            os.getenv("LETTER_DB_PORT", "3306"),
            os.getenv("LETTER_DB_NAME", "xinfang"),
        ),
    },
    "prod": {
        "host": "0.0.0.0",  # Docker容器内监听所有接口
        "port": 8106,
        "db_pool": DB_POOL_CONFIG,
        "database_url": build_database_url(
            os.getenv("LETTER_DB_USER", "root"),
            os.getenv("LETTER_DB_PASSWORD", ""),
            os.getenv("LETTER_DB_HOST", "localhost"),
            os.getenv("LETTER_DB_PORT", "3306"),
            os.getenv("LETTER_DB_NAME", "xinfang"),
        ),
    },
}

# 获取当前环境的配置
current_config = config[ENV]
